package com.ruoyi.common.httpSdk.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.exception.ParamDeficiencyException;
import com.ruoyi.common.httpSdk.AbstractResponse;
import com.ruoyi.common.httpSdk.Client;
import com.ruoyi.common.httpSdk.request.Request;
import com.ruoyi.common.httpSdk.util.HttpRequest;
import com.ruoyi.common.httpSdk.util.ParserFactory;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.util.Map;

@Getter
@Setter
@Slf4j
public class CommonClient implements Client {

    public static final String CHARSET_UTF8 = "UTF-8";
    private int connectTimeout;
    private int readTimeout;


    public CommonClient() {
        this.connectTimeout = 10000;
        this.readTimeout = 10000;
    }

    @Override
    public <T extends AbstractResponse> T execute(Request<T> request) throws Exception {

        String apiUrl = request.getApiUrl();

        if(StringUtils.isEmpty(apiUrl)){
            throw new ParamDeficiencyException("初始化sdk客户端失败");
        }
        String responseMsg = "";
        try {
            switch (request.getMethod()){
                case "POST":
                    responseMsg = HttpRequest.sendPostRequest(apiUrl,(Map)request.getUrlParams(),request.getContentType());
                    break;
                case "GET":
                    apiUrl = buildGetParams(request);
                    responseMsg = HttpRequest.sendGetRequest(apiUrl);
                    break;
                default:
            }
            log.debug("Sdk response message json:" + responseMsg);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("【调用sdk出现异常 url:{"+request.getApiUrl()+"} 报错文本:{"+e.getMessage()+"}】");
        }

        String jsonStr = machineJson(responseMsg,request);

        return this.parser(jsonStr,request.getResponseClass());
    }

    private <T extends AbstractResponse> String buildGetParams(Request<T> request) {
        StringBuilder apiUri = new StringBuilder(request.getApiUrl());
        Map<String,Object> params = (Map)request.getUrlParams();
        int i = 0;
        for (String key : params.keySet()) {
            if(i == 0){
                apiUri.append("?");
            }else{
                apiUri.append("&");
            }
            apiUri.append(key);
            apiUri.append("=");
            apiUri.append(params.get(key).toString());
            i++;
        }
        return apiUri.toString();
    }

    private String machineJson(String responseMsg, Request request) throws Exception {

        JSONObject resJson = JSON.parseObject(responseMsg);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("code",resJson.getIntValue("status"));
        jsonObject.put("url",request.getApiUrl());
        jsonObject.put("message",resJson.getString("message"));
        jsonObject.put("resData",responseMsg);

        //获取泛型类
        Class cls;
        try {
            cls = (Class)((ParameterizedType)request.getResponseClass().getGenericSuperclass()).getActualTypeArguments()[0];
        } catch (Exception e) {
            throw new Exception(e);
        }
        jsonObject.put("data", JSON.parseObject(responseMsg,cls));
        return jsonObject.toJSONString();
    }

    private <T extends AbstractResponse> T parser(String responseMsg, Class<T> responseClass) throws Exception {
        return ParserFactory.JSON_PARSER.parse(responseMsg,responseClass);
    }
}
